package com.book.deprecated.state;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class DeprecatedPayOrder extends DeprecateAbstractOrderState{
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private DeprecatedSendOrder deprecatedSendOrder;

    @Override
    protected DeprecatedOrder payOrder(String orderId, DeprecatedOrderContext context) {
         String orderStr = redisTemplate.opsForValue().get(orderId);
        if (StringUtils.isBlank(orderStr)) {
            throw new RuntimeException("订单不存在");
        }
        DeprecatedOrder order = JSON.parseObject(orderStr, DeprecatedOrder.class);
        if (!order.getState().equals(ORDER_WAIT_PAY)) {
            throw new UnsupportedOperationException("这个订单应该是 待发货状态 但是此时是"+order.getState());
        }

        order.setState(ORDER_WAIT_SEND);
        redisTemplate.opsForValue().set(orderId,JSON.toJSONString(order));

        context.setCurrentState(this.deprecatedSendOrder);
        return order;
    }
}
